<template>
  <view class="MyUploader">
    <view class="uploader">
      <van-button
        color="#05A47D"
        size="small"
        custom-style="border-radius:0"
        @click="uploadFileContent"
      >
        + 上传文件</van-button
      >
      <text style="font-size: 22rpx; color: #aaa"
        >（一个任务最多只能拥有三个文件）</text
      >
    </view>
    <view style="font-size: 28rpx" v-if="fileList.length || tempFiles.length"
      >已有文件：</view
    >
    <view class="fileContainer">
      <view
        class="fileItem"
        v-for="(item, index) in fileList"
        :key="index"
        @click="downLoadPreviewFile(item.fileID)"
      >
        <view class="icon avatar">
          <image :src="item.author.avatar"></image>
        </view>
        <view class="name">{{ item.author.nickName }}:</view>
        <view class="icon">
          <image :src="fileExtImg(item.fileName)"></image>
        </view>
        <view class="fileName">{{ item.fileName }}</view>
      </view>
      <view
        class="fileItem"
        v-for="(item, index) in tempFiles"
        :key="index"
        @click="previewFile(item.path)"
      >
        <view class="icon avatar">
          <image :src="item.author.avatar"></image>
        </view>
        <view class="name">{{ item.author.nickName }}:</view>
        <view class="icon">
          <image :src="fileExtImg(item.name)"></image>
        </view>
        <view class="fileName">{{ item.name }}</view>
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "MyUploader",
  props: {
    fileList: {
      type: Array,
    },
  },
  data() {
    return {
      tempFiles: [],
      fileImages: {
        docx: "../../static/image/word.png",
        xlsx: "../../static/image/excel.png",
        ppt: "../../static/image/ppt.png",
        pdf: "../../static/image/pdf.png",
      },
    };
  },
  computed: {
    ...mapState(["userInfo"]),
    fileExtImg() {
      return (fileName) => {
        return this.fileImages[fileName.split(".").pop()]
      };
    },
  },
  methods: {
    // 选择需要上传的文件
    uploadFileContent() {
      if (this.fileList.length + this.tempFiles.length >= 3) {
        uni.showToast({
          icon: "error",
          title: "文件数过多",
        });
        return;
      }
      wx.chooseMessageFile({
        count: 1,
        success: (res) => {
          console.log(res.tempFiles);
          const tempFile = res.tempFiles[0];
          tempFile.author = {
            nickName: this.userInfo.nickName,
            avatar: this.userInfo.avatar,
          };
          if (!this.fileImages[tempFile["name"].split(".").pop()]) {
            uni.showToast({
              icon: "error",
              title: "不支持该文件",
            });
          } else {
            this.tempFiles.push(tempFile);
          }
        },
      });
    },
    // 确认上传，将上传文件上传至云存储
    uploadFileToDB() {
      const fileTasks = [];
      this.tempFiles.forEach((item) => {
        fileTasks.push(
          wx.cloud.uploadFile({
            cloudPath: `editorFile/${Math.floor(new Date().getTime() / 1000)}-${
              item.name
            }`,
            filePath: item.path,
          })
        );
      });
      return Promise.all(fileTasks);
    },
    previewFile(filePath) {
      wx.openDocument({
        showMenu: true,
        filePath,
      });
    },
    downLoadPreviewFile(fileID) {
      uni.showLoading({
        title: "下载文件中",
      });
      wx.cloud.downloadFile({
        fileID,
        success: (res) => {
          console.log("downLoad:", res);
          wx.openDocument({
            showMenu: true,
            filePath: res.tempFilePath,
          });
        },
        complete: () => {
          uni.hideLoading();
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.MyUploader {
  .fileItem {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    margin-top: 15rpx;
    .icon {
      width: 50rpx;
      height: 50rpx;
      margin-right: 15rpx;
      image {
        width: 100%;
        height: 100%;
      }
    }
    .avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      overflow: hidden;
    }
    .name {
      margin-right: 20rpx;
    }
    .fileName {
      width: 250rpx;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      text-decoration: underline;
    }
  }
  .uploader {
    margin-bottom: 20rpx;
  }
}
</style>
